package cn.com.ustudy.course.core.web.ctrl;

import cn.hutool.core.util.IdUtil;
import cn.melonlib.cores.commons.comp.web.ctrl.BasicController;
import cn.melonlib.cores.jpa.model.bean.collections.JsonMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping(path = {"/ck/images"})
public class CkImagesController extends BasicController{

    @Value("${resource.web.store.upload:/service/resources/upload}")
    private String uploadRootPath;

    @Value("${resource.web.store.course:/course}")
    private String ckCourseImgRoot;


    @PostMapping(path = "courseMemoUpload/{courseId}.api",produces = {BasicController.APPLICATION_JSON_UTF8_VALUE})
    public String courseMemoUpload(
        MultipartHttpServletRequest request,@PathVariable("courseId")String courseId
    ) throws Exception{
        MultipartFile file=request.getFile("upload");
        String base=request.getHeader("root");
        String path=new StringBuilder(ckCourseImgRoot).append("/")
                .append(courseId).append("/memo")
                .append(DateFormatUtils.format(System.currentTimeMillis(),"/yyyy/MM/dd/HH/mm"))
                .append(IdUtil.fastSimpleUUID()).append(".")
                .append(FilenameUtils.getExtension(file.getOriginalFilename())).toString();
        File store=new File(uploadRootPath,path);
        FileUtils.forceMkdirParent(store);
        try(InputStream in=file.getInputStream(); OutputStream out=new FileOutputStream(store)){
            StreamUtils.copy(in,out);
        }
        return JsonMap.createMap().append("status",true).append("url",base+"/ck/images"+path).jsonString();
    }

    @GetMapping(path = "/**")
    public void images(
            HttpServletRequest request, HttpServletResponse response
            ) throws Exception{
        String path=request.getServletPath();
        path=path.replace("/ck/images",uploadRootPath);
        File store=new File(path);
        this.downloadConfig(request,response,store.getName(),store.length(),"image/*");
        try(InputStream in=new FileInputStream(store);OutputStream out=response.getOutputStream()){
            StreamUtils.copy(in,out);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
